<template>
  <div>
    发现·视频
    <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        style="display: block"
        @click="drawer = true"
    >新增发现视频
    </el-button
    >
    <div v-for="v in videolist" :key="v.id" class="videodiv">
      <video
          width="320"
          height="240"
          controls
          class="video"
          controlslist="nodownload"
      >
        <source :src="$cosurl + v.url" type="video/mp4"/>
        您的浏览器不支持Video标签。
      </video>
      <el-popconfirm
          @confirm="deldiscovervideo(v.id)"
          confirmButtonText="好的"
          cancelButtonText="不用了"
          icon="el-icon-info"
          iconColor="red"
          title="确定删除这个视频吗？"
      >
        <template #reference>
          <el-button
              type="danger"
              icon="el-icon-delete-solid"
              style="margin-top: 5%; margin-bottom: 5%"
          >删除视频
          </el-button
          >
        </template>
      </el-popconfirm>
    </div>
    <el-drawer
        title="新增发现视频"
        v-model="drawer"
        :direction="direction"
        :before-close="handleClose"
        destroy-on-close
    >
      <div class="demo-drawer__content">
        <el-upload
            :on-change="befup"
            class="upload-demo"
            :auto-upload="false"
            :on-remove="del"
            drag
            action="https://maisheng-1305747968.cos.ap-nanjing.myqcloud.com"
            multiple
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip">请上传视频文件</div>
          </template>
        </el-upload>
        <el-progress
            :text-inside="true"
            :stroke-width="20"
            :percentage="percentage"
            status="exception"
            v-show="pshow"
        ></el-progress>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {ElMessage} from "element-plus";

export default {
  name: "FaXian",
  props: ["jwttoken"],
  data() {
    return {
      drawer: false,
      cos: {},
      percentage: 0,
      pshow: false,
      videolist: [],
      level: 0,
      isActive: false,
      url: '',
    };
  },
  created: function () {
    this.gettmpcos();
    this.getfileList();
  },
  methods: {
    handleClose(done) {
      if (this.loading) {
        return;
      }
      this.loading = true;
      this.timer = setTimeout(() => {
        done();
        // 动画关闭需要一定的时间
        setTimeout(() => {
          this.loading = false;
        }, 400);
      }, 400);
    },
    cancelForm() {
      this.loading = false;
      this.dialog = false;
      clearTimeout(this.timer);
    },
    gettmpcos: function () {
      console.log("cos");
      let that = this;
      var cos = new this.$COS({
        getAuthorization: function (options, callback) {
          console.log(options);
          console.log(callback);
          // 异步获取临时密钥
          //   $.get(
          //     "http://example.com/server/sts.php",
          //     {
          //       bucket: options.Bucket,
          //       region: options.Region,
          //     },
          //     function (data) {
          //       var credentials = data && data.credentials;
          //       if (!data || !credentials)
          //         return console.error("credentials invalid");

          //     }
          //   );

          that.$jquery.ajax({
            async: false,
            type: "GET",
            dataType: "json",
            url: that.$baseurl + "createCosTmp",
            beforeSend: function (request) {
              request.setRequestHeader("Authorization", that.jwttoken);
            },
            success: function (rtn) {
              if (rtn.code == -5) {
                that.$emit("loginstate1", -1);
              }
              if (rtn.code == 1) {
                var credentials = rtn.data && rtn.data.credentials;
                if (!rtn.data || !credentials)
                  return console.error("credentials invalid");
                callback({
                  TmpSecretId: credentials.tmpSecretId,
                  TmpSecretKey: credentials.tmpSecretKey,
                  SecurityToken: credentials.sessionToken,
                  // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                  StartTime: rtn.data.startTime, // 时间戳，单位秒，如：1580000000
                  ExpiredTime: rtn.data.expiredTime, // 时间戳，单位秒，如：1580000900
                });
              }
            },
          });
        },
      });
      console.log(cos);
      this.cos = cos;
    },
    befup: function (file, filelist) {
      // this.temp(file)
      console.log(filelist);
      // console.log(file.raw);
      let that = this;
      let key = that.randomString();
      this.cos.putObject(
          {
            Bucket: "maisheng-1305747968" /* 必须 */,
            Region: "ap-nanjing" /* 存储桶所在地域，必须字段 */,
            Key: key + ".mp4" /* 必须 */,
            StorageClass: "STANDARD",
            Body: file.raw, // 上传文件对象
            onProgress: function (progressData) {
              that.pshow = true;
              console.log(progressData.percent);
              that.percentage = progressData.percent.toFixed(2) * 100;
            },
          },
          function (err, data) {
            console.log(err || data);
            if (err) {
              that.$notify.error({
                title: "错误",
                message: "上传失败",
              });
            } else {
              that.$notify({
                title: "成功",
                message: "上传成功",
                type: "success",
              });
              that.pshow = false;
              file.key = key + '.mp4';
              that.url = key + '.mp4'
              that.uploadsql()
            }
          }
      );
    },

    uploadsql: function () {
      let that = this
      this.$jquery.ajax({
        async: false,
        type: "post",
        dataType: "json",
        url: that.$baseurl + "addDisVideo",
        data: {
          url: that.url
        },
        beforeSend: function (request) {
          request.setRequestHeader("Authorization", that.jwttoken);
        },
        success: function (rtn) {
          if (rtn.code == -5) {
            that.$emit("loginstate1", -1);
          }
        },
      });
    },
    randomString: function () {
      let e = 32;
      let t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
      let a = t.length;
      let n = "";
      for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
      return n;
    },
    // del: function (file, fileList) {
    //   console.log(file.key);
    //   let key = file.key;
    //   console.log(fileList);
    //   this.delvideo(key);
    // },
    deldiscovervideo: function (id) {
      let that = this;
      this.$jquery.ajax({
        async: false,
        type: "delete",
        dataType: "json",
        url: that.$baseurl + "deleteDisVideo",
        data: {
          id: id,
        },
        beforeSend: function (request) {
          request.setRequestHeader("Authorization", that.jwttoken);
        },
        success: function (rtn) {
          if (rtn.code == -5) {
            that.$emit("loginstate1", -1);
          }else{
            if (rtn.code == 1) {
              that.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
              });
              setTimeout(() => {
                window.location.reload();
              }, 1000);
            }else{
              that.$notify({
                title: "失败",
                message: rtn.msg,
                type: "error",
              });
            }
          }

        },
      });
    },
    getfileList: function () {
      let that = this;
      this.$jquery.ajax({
        async: false,
        type: "GET",
        dataType: "json",
        url: that.$baseurl + "getDisVideoList",
        beforeSend: function (request) {
          request.setRequestHeader("Authorization", that.jwttoken);
        },
        success: function (rtn) {
          if (rtn.code == -5) {
            that.$emit("loginstate1", -1);
          }
          if (rtn.code == 1) {
            that.videolist = rtn.data;
          }else{
            ElMessage.error(rtn.msg)
          }
        },
      });
    },

  },
}
</script>

<style scoped>
.video {
  display: block;
}

.videodiv {
  display: inline-block;
  margin-left: 10%;
}

.delvideo {
  display: inline-block;
  text-align: center;
}

.el-icon-refresh {
  width: 100px;

}

.el-icon-refresh:hover {
  color: red;

}

.flushcls {
  /*transform: rotate(300deg) ;*/
  /*transform-style:preserve-3d;*/
  animation: turn 1s linear infinite;

}

@keyframes turn {
  0% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
  }
  25% {
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
  }
  50% {
    -webkit-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
  }
  75% {
    -webkit-transform: rotate(270deg);
    -moz-transform: rotate(270deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    -moz-transform: rotate(360deg);
  }
}

</style>
